package org.szpshang.framework.support.dao.hibernate.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.szpshang.bean.JsonDataBean;
import org.szpshang.framework.support.dao.hibernate.HibernateDao;

public class HibernateDaoSupport implements HibernateDao {

	@Autowired
	@Qualifier("sessionFactory")
	private SessionFactory sessionFactory;

	protected Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	@SuppressWarnings("unchecked")
	public <T> T get(Class<T> t,Integer id) {
		return (T) getSession().get(t, id);
	}
	
	
	public Serializable save(Object entity) {
		return getSession().save(entity);
	}

	public void update(Object entity) {
		getSession().update(entity);
	}
	
	public void delete(List<?> entityList) {
		for (Object t : entityList) {
			delete(t);
		}
	}

	public void delete(Object entity) {
		getSession().delete(entity);
	}
	
	public void delete(Class<?> t,Integer... ids) {
		for (Integer id : ids) {
			delete(get(t,id));
		}
	}
	
	public List<?> findByHQL(String hql) {
		return getSession().createQuery(hql).list();
	}

	public JsonDataBean findPageByHql(int pageNo, int pageSize, String hql, Object... params) {
		
		JsonDataBean j = new JsonDataBean(true);
		int pos = hql.toLowerCase().indexOf("from");
		String tmp = "";
		if (pos != -1) {
			tmp = "select count(*) "+hql.substring(pos);
			System.out.println(tmp);
		}
		Query q = setParamerter(tmp,params);
		
		int total = Integer.valueOf(q.uniqueResult().toString());
		j.setTotalCount(total);
		
		Query query = setParamerter(hql,params);
		
		query.setFirstResult((pageNo - 1) * pageSize);
		query.setMaxResults(pageSize);
		j.setData(query.list());
		
		return j;
		
		
	}
	
	private Query setParamerter(String hql, Object[] params){
		Query query = getSession().createQuery(hql);
		int index=0;
		for(Object o:params){
			query.setParameter(index++, o);
		}
		return query;
	}



	

}
